LoginSignup
15
13

More than 5 years have passed since last update.

jQueryの .on でハマった話

Last updated at Posted at 2018-10-24

スマホでスクロールを禁止する記述を追加した

$(document).on('touchmove', function(e) {e.preventDefault();});

すると以下の警告が表示される

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. 
See https://www.chromestatus.com/features/5093566007214080
preventDefault @ jquery-1.11.2.min.js:3 (anonymous)

URLが表示されているので中を見てみると

AddEventListenerOptions defaults passive to false. 
With this change touchstart and touchmove listeners added to the document will default to passive:true 
(so that calls to preventDefault will be ignored)..

If the value is explicitly provided in the AddEventListenerOptions it will continue having the value specified by the page.

This is behind a flag starting in Chrome 54, and enabled by default in Chrome 56. 
See https://developers.google.com/web/updates/2017/01/scrolling-intervention

Chrome56以降はデフォルトで passive:true になっているからスクロールできないよって言ってますね
理由は知らないですが、 passive: false を渡してあげるように修正してみます


$(document).on('touchmove', function(e) {e.preventDefault();}, {passive: false});

すると新規に以下のエラー

TypeError: ((m.event.special[e.origType] || {}).handle || e.handler).apply is not a function

何について怒られているのか全くわからない件・・・エラーの意味ないでしょこれ

jQuery側のエラーなので、記述方法について調べてみます。今回使ってるのは .on ですね
公式リファレンスを見てみます(http://api.jquery.com/on/
.on(events[,selector][,data],handler) と書かれていて、これを見る限りhandlerの後ろに第三引数で passive: false を渡すのは無理っぽいですね。ナンテコッタ

解決

素のJSのAddEventListenerのリファレンスを見てみます(https://developer.mozilla.org/ja/docs/Web/API/EventTarget/addEventListener
target.addEventListener(type, listener[, options]); と書かれていますね!こちらは options としてオブジェクトが渡せそうです。記述方法を下記の様に変えてみます


document.addEventListener('touchmove', function(e) {e.preventDefault();}, {passive: false});

エラー無し。スクロール制御ができました。
jQueryじゃ本当に無理なのかな?一旦これで。

15
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
13